import axios from 'axios'

import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
} from 'axios'

const { MODE, VITE_API_URL } = import.meta.env;
const baseURL = MODE === 'development' ? '' : VITE_API_URL;

const instance: AxiosInstance = axios.create({
  timeout: 30000,
  baseURL,
  withCredentials: true
})

instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // token验证，请求处理等
    config.headers['Authorization'] = `Bearer ${sessionStorage.getItem('token')}`;

    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 导出处理
    if (response.request.responseURL.includes('export')) {
      return response.data
    } else {
      const res = response.data
      // 此处code根据业务规定code处理
      if (res.code == '200') {
        return res.data
      } else {
        // 错误处理
        // alert(res.msg);
        return Promise.reject(res.msg)
      }
    }
  },
  (error: AxiosError) => {
    // http错误处理
    let message = ''
    // HTTP 状态码
    const status = error.response?.status
    switch (status) {
      case 401:
        message = 'token 失效，请重新登录'
        window.location.href = '/login'
        break
      case 403:
        message = '拒绝访问'
        break
      case 404:
        message = '请求地址错误'
        break
      case 500:
        message = '服务器故障'
        break
      default:
        message = '网络连接故障'
    }
    console.log(message);
    return Promise.reject(error)
  },
)

export const http = {
  // get请求
  get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return instance.get(url, config)
  },

  // post请求
  post<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return instance.post(url, data, config)
  },

  // put请求
  put<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return instance.put(url, data, config)
  },

  // delete请求
  delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return instance.delete(url, config)
  },
}
